import pygame
import closing, confirmtomenu, credits, gameover, gamestate, ingame, intro
import leveladvance, mainmenu, paused

class StateManager():
    """Manages game states"""
    
    def __init__(self, dimensions, default='intro'):
        self._isRunning = True
        gamestate.GameState.validStates = {
                            'intro': intro.Intro(),
                            'mainmenu': mainmenu.MainMenu(),
                            'ingame': ingame.InGame(),
                            'paused': paused.Paused(),
                            'leveladvance': leveladvance.LevelAdvance(),
                            'gameover': gameover.GameOver(),
                            'confirm2menu': confirmtomenu.ConfirmToMenu(),
                            'credits': credits.Credits(),
                            'closing': closing.Closing()}
        
        if gamestate.GameState.validStates[default]:
            self.currentState = gamestate.GameState.validStates[default]
        else:
            self.currentState = gamestate.GameState.validStates['intro']
            
        self.background = pygame.Surface(dimensions)
        self.background.fill((0, 0, 0))
    
    def draw(self, screen):
        screen.blit(self.background, (0, 0))
        self.currentState.draw(screen)
        pygame.display.flip()
    
    def handle_events(self, events, mods):
        self.currentState.handle_events(events, mods)
    
    def is_running(self):
        return self._isRunning
    
    def update(self, etime):
        self._lastState = self.currentState
        self.currentState = self.currentState.update(etime)
        if self.currentState and not self._lastState == self.currentState:
            self.currentState.enter_state()
        if not self.currentState:
            self._isRunning = False